package com.xuhuan.thread.study2;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author huan.xu
 * @date 2021/9/29 19:34
 * @description ReentrantLock 案例: 可重入锁
 */
public class ReentrantLockDemo {

    public static void main(String[] args) {
        BuyTicker buyTicker = new BuyTicker();

        new Thread(buyTicker).start();
        new Thread(buyTicker).start();
        new Thread(buyTicker).start();
    }
}

/**
 * 买票
 */
class BuyTicker implements Runnable {

    private int tickerNums = 10;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();

                if (tickerNums > 0) {
                    System.out.println(tickerNums--);
                } else {
                    break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }
}